package edge.display.backend.MsgDistributer.WebSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edge.display.backend.MsgHandler.RespHandler;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

@ServerEndpoint("/websocket/{name}")
@Component
public class WebSocketServer {

    //store the connect session
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
    private static Logger logger = Logger.getLogger(WebSocketServer.class.getName());

    // 单播（一对一）
    public static void unicast(String message, String key) throws IOException {
        Session session = sessionPools.get(key);
        if (session != null) {
            unicast(message, session);
        } else {
            logger.log(Level.parse("error"), String.format("has not connected to %s", key));
        }
    }

    private static void unicast(String message, Session session) throws IOException {
        synchronized (session) {
            session.getBasicRemote().sendText(message);
        }
    }

    // 广播（一对多）
    private static void broadcast(String message) throws IOException {
        for (Session session : sessionPools.values()) {
            unicast(message, session);
        }
    }

    public static void broadcast(Map<String, ?> map) throws IOException {
        broadcast(JSONObject.toJSONString(map));
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String userName) {
        System.out.println("[WebSocket] successfully connected to " + userName);
        sessionPools.put(userName, session);
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "name") String userName) {
        sessionPools.remove(userName);
        System.out.println("[WebSocket] disconnect to " + userName);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("[WebSocket] new message:" + message);
        synchronized (session) {
            JSONObject jsonObject = JSON.parseObject(message);
            JSONObject resJSONObject = RespHandler.onHello(jsonObject);
            unicast(resJSONObject.toJSONString(), session);
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("[WebSocket] error");
        throwable.printStackTrace();
    }
}
